// 方块类型和形状定义
const BLOCK_TYPES = {
    I: {
        shape: [
            [0, 0, 0, 0],
            [1, 1, 1, 1],
            [0, 0, 0, 0],
            [0, 0, 0, 0]
        ],
        color: '#00FFFF' // 青色
    },
    J: {
        shape: [
            [1, 0, 0],
            [1, 1, 1],
            [0, 0, 0]
        ],
        color: '#0000FF' // 蓝色
    },
    L: {
        shape: [
            [0, 0, 1],
            [1, 1, 1],
            [0, 0, 0]
        ],
        color: '#FF7F00' // 橙色
    },
    O: {
        shape: [
            [1, 1],
            [1, 1]
        ],
        color: '#FFFF00' // 黄色
    },
    S: {
        shape: [
            [0, 1, 1],
            [1, 1, 0],
            [0, 0, 0]
        ],
        color: '#00FF00' // 绿色
    },
    T: {
        shape: [
            [0, 1, 0],
            [1, 1, 1],
            [0, 0, 0]
        ],
        color: '#800080' // 紫色
    },
    Z: {
        shape: [
            [1, 1, 0],
            [0, 1, 1],
            [0, 0, 0]
        ],
        color: '#FF0000' // 红色
    }
};

class Block {
    constructor(type) {
        this.type = type || this.randomType();
        this.shape = BLOCK_TYPES[this.type].shape;
        this.color = BLOCK_TYPES[this.type].color;
        this.rotation = 0;
        this.x = 3; // 初始水平位置（居中）
        this.y = 0; // 初始垂直位置（顶部）
    }

    randomType() {
        const types = Object.keys(BLOCK_TYPES);
        return types[Math.floor(Math.random() * types.length)];
    }

    // 获取当前旋转状态下的形状
    getCurrentShape() {
        let shape = JSON.parse(JSON.stringify(this.shape));
        for (let i = 0; i < this.rotation; i++) {
            shape = this.rotateMatrix(shape);
        }
        return shape;
    }

    // 矩阵旋转（顺时针90度）
    rotateMatrix(matrix) {
        const rows = matrix.length;
        const cols = matrix[0].length;
        const result = Array(cols).fill().map(() => Array(rows).fill(0));

        for (let row = 0; row < rows; row++) {
            for (let col = 0; col < cols; col++) {
                result[col][rows - 1 - row] = matrix[row][col];
            }
        }

        return result;
    }

    // 旋转方块
    rotate() {
        this.rotation = (this.rotation + 1) % 4;
    }

    // 移动方块
    move(dx, dy) {
        this.x += dx;
        this.y += dy;
    }

    // 获取方块所有格子的坐标
    getCells() {
        const shape = this.getCurrentShape();
        const cells = [];

        for (let row = 0; row < shape.length; row++) {
            for (let col = 0; col < shape[row].length; col++) {
                if (shape[row][col]) {
                    cells.push({
                        x: this.x + col,
                        y: this.y + row
                    });
                }
            }
        }

        return cells;
    }
}